/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package botobjects;

import interfaces.BotObject;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import main.CommonMethods;
import main.Constants;
import main.UserCentral;

import org.apache.log4j.Logger;

import tools.StringTools;

import commandhandlers.SpellsOpsHandler;

import database.DBConnectionFactory;

/**
 * This class represents an instant damage spell or op, such as NS
 * 
 * 
 */
public class InstantDamageSpellOp implements BotObject {
   public static List<InstantDamageSpellOp> getInstantDamageSpellOp(final int type, final String... args) {
	  List<InstantDamageSpellOp> out = new LinkedList<InstantDamageSpellOp>();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 if (type == Constants.IDSPELLOP_GET_FOR_SPELLOP && args.length == 1) {
			ps = DBConnectionFactory
				  .getConnectionHandler()
				  .getConnection()
				  .prepareStatement(
						"SELECT * FROM " + "idspellop,province WHERE spellop = ? AND idspellop.province = province.name");
			ps.setString(1, args[0]);
		 } else if (type == Constants.IDSPELLOP_GET_FOR_SPELLOP_FOR_KD && args.length == 2) {
			ps = DBConnectionFactory
				  .getConnectionHandler()
				  .getConnection()
				  .prepareStatement(
						"SELECT * FROM "
							  + "idspellop,province WHERE spellop = ? AND kdloc = ? AND idspellop.province = province.name");
			ps.setString(1, args[0]);
			ps.setString(2, args[1]);
		 } else if (type == Constants.IDSPELLOP_GET_FOR_SPELLOP_FOR_PROV && args.length == 2) {
			ps = DBConnectionFactory
				  .getConnectionHandler()
				  .getConnection()
				  .prepareStatement(
						"SELECT * FROM "
							  + "idspellop,province WHERE spellop = ? AND province = ? AND idspellop.province = province.name");
			ps.setString(1, args[0]);
			ps.setString(2, args[1]);
		 } else if (type == Constants.IDSPELLOP_GET_FOR_SPELLOP_FOR_PLAYER && args.length == 2) {
			ps = DBConnectionFactory
				  .getConnectionHandler()
				  .getConnection()
				  .prepareStatement(
						"SELECT * FROM "
							  + "idspellop,province WHERE spellop = ? AND nick = ? AND idspellop.province = province.name");
			ps.setString(1, args[0]);
			ps.setString(2, args[1]);
		 }
		 if (ps != null) {
			rs = ps.executeQuery();
			while (rs.next()) {
			   out.add(new InstantDamageSpellOp(rs.getString("province"), rs.getString("kdloc"), rs.getString("spellop"), rs
					 .getInt("result"), rs.getInt("times"), rs.getString("nick")));
			}
		 }
	  } catch (SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (Exception e) {
		 }
		 try {
			ps.close();
		 } catch (Exception e) {
		 }
	  }
	  return out;
   }

   private String provname = "";
   private String kd = "";
   private String name = "";
   private int results = 0;
   private int times = 0;

   private String sender = "";

   public InstantDamageSpellOp(final String provname, final String kd, final String name, final int results, final int times,
		 final String sender) {
	  this.provname = provname;
	  this.kd = kd;
	  this.name = name;
	  this.results = results;
	  this.times = times;
	  this.sender = sender;
   }

   @Override
   public List<String> getIRCOutput(final int outputType, final String... args) {
	  // ops like these have their own handlers
	  return new LinkedList<String>();
   }

   public String getKd() {
	  return kd;
   }

   public String getName() {
	  return name;
   }

   public String getProvname() {
	  return provname;
   }

   public int getResults() {
	  return results;
   }

   @Override
   public Map<String, Object> getRPCOutput(final int... includes) {
	  Map<String, Object> out = new HashMap<String, Object>();
	  if (StringTools.isNullOrEmpty(getProvname()) || StringTools.isNullOrEmpty(getKd()) || StringTools.isNullOrEmpty(getName())
			|| StringTools.isNullOrEmpty(getSender()) || getResults() < 0 || getTimes() < 0)
		 return out;
	  out.put("Province", getProvname());
	  out.put("KD", getKd());
	  out.put("Name", getName());
	  out.put("Results", getResults());
	  out.put("Times", getTimes());
	  out.put("Player", getSender());
	  return out;
   }

   public String getSender() {
	  return sender;
   }

   public int getTimes() {
	  return times;
   }

   /**
    * The message to print when this object has been saved
    * 
    * @return String with a message to show the object was saved
    */
   public String printSave() {
	  if (StringTools.isNullOrEmpty(getProvname()) || StringTools.isNullOrEmpty(getName()))
		 return "";
	  return getName() + " for " + getProvname() + " added";
   }

   @Override
   public boolean saveToDB() {
	  boolean out = false;
	  String mainnick = UserCentral.getInstance().getOnlineUser(sender);
	  if ("".equals(getProvname())) {
		 if ("".equals(SpellsOpsHandler.getSpellOpTarget(mainnick)))
			return out;
		 else {
			provname = SpellsOpsHandler.getSpellOpTarget(mainnick);
			Province prov = Province.getProvince(provname);
			if (prov == null)
			   return out;
			else {
			   kd = prov.getKd();
			}
		 }
	  } else {
		 if (!"".equals(getKd()) && !CommonMethods.kdExists(getKd())) {
			if (!CommonMethods.addDefaultKD(getKd()))
			   return out;
		 }
		 if ("".equals(CommonMethods.provinceExists(getProvname()))) {
			if (!new Province(getProvname(), getKd(), "", "", "", 0, 0).saveToDB())
			   return out;
		 }
	  }
	  if (StringTools.isNullOrEmpty(getProvname()) || StringTools.isNullOrEmpty(getKd()) || StringTools.isNullOrEmpty(getName())
			|| StringTools.isNullOrEmpty(getSender()) || getResults() < 0 || getTimes() < 0)
		 return out;
	  CommonMethods.addAction(mainnick, getName());
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM " + "idspellop WHERE nick = ? AND province = ? AND spellop = ?");
		 ps.setString(1, mainnick);
		 ps.setString(2, getProvname());
		 ps.setString(3, getName());
		 rs = ps.executeQuery();

		 if (rs.next()) {
			int result = rs.getInt("result") + getResults();

			try {
			   ps.close();
			} catch (final Exception e) {
			}

			ps = DBConnectionFactory
				  .getConnectionHandler()
				  .getConnection()
				  .prepareStatement(
						"UPDATE idspellop SET " + "result = ?, times = times + 1 WHERE nick = ? AND province = ? AND spellop = ?");
			ps.setInt(1, result);
			ps.setString(2, mainnick);
			ps.setString(3, getProvname());
			ps.setString(4, getName());
			ps.executeUpdate();
		 } else {
			try {
			   ps.close();
			} catch (final Exception e) {
			}

			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("INSERT INTO idspellop VALUES(?,?,?,?,1)");
			ps.setString(1, mainnick);
			ps.setString(2, getProvname());
			ps.setString(3, getName());
			ps.setInt(4, getResults());
			ps.executeUpdate();
		 }
		 out = true;
	  } catch (SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (Exception e) {
		 }
		 try {
			ps.close();
		 } catch (Exception e) {
		 }
	  }
	  return out;
   }
}
